import { useReducer } from "react";
import "./App.css";

function queryData() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(666)
        }, 2000)
    })
}

function App() {
    /* 
      useReducer
    */
    function reducer (state, action) {
        switch (action.type) {
            case 'increment_age': 
                // 不能直接修改state的状态再return，否则无法触发重新渲染
                // state.age += 1
                // return state
                return {
                    age: state.age + 1,
                    name: state.name
                };
            case 'changed_name': {
                return {
                    age: state.age,
                    name: action.nextName
                };
            }
        }
        throw new Error('Unknown Action' + action.type)
    }
    // item是状态，dispatch允许更新状态并触发重新渲染
    // {age: 23是初始状态}
    const [item, dispatch] = useReducer(reducer, {age: 23, name: ''})
    return (
        <>
        <div className="card">
            <div onClick={() => dispatch({type: 'increment_age'})}>增加年龄</div>
            <input onChange={(e) => dispatch({type: 'changed_name', nextName: e.target.value })} value={item.name} placeholder={item.name ? item.name : '修改名称'} />
            {/* 注意是item.age，不是直接渲染age */}
            <div>Hello, your age is {item.age}</div>
        </div>
        </>
    );
}

export default App;
